{% extends 'layout/manage.html' %}
{% load static %}
{% block css %}
    <style>
        .panel-body {
            padding: 0;
        }

        .err-msg {
            color: red;
            position: absolute;
        }

        .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .panel-default > .panel-heading .function .upload {
            overflow: hidden;
        }

        .panel-default > .panel-heading .function input {
            opacity: 0;
            position: absolute;
            top: 80px;
            bottom: 0;
            width: 90px;
            right: 100px;
            overflow: hidden;
        }

        .upload-progress {
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 400px;
        }
    </style>
{% endblock %}
{% block content %}
    <div class="container-fluid">
        <div class="panel panel-default">
            <div class="panel-heading ">
                <div>
                    <a href="{% url 'file' project_id=request.tracer.project.id %}">
                        <i class="fa fa-folder" aria-hidden="true">&nbsp;文件库</i></a>
                    {% for path in path_list %}
                        <a href="{% url 'file' project_id=request.tracer.project.id %}?folder={{ path.id }}">
                            <i class="fa fa-angle-right" aria-hidden="true"></i>
                            <span>{{ path.name }}</span>
                        </a>
                    {% endfor %}
                </div>
                <div class="function">
                    <div class="btn btn-primary btn-xs upload">
                        <div><i class="fa fa-upload" aria-hidden="true"></i> 上传文件</div>
                        <input type="file" multiple name="uploadFile" id="uploadFile">
                    </div>
                    <a type="button" href="#"
                       class="btn btn-success btn-xs" data-toggle="modal" data-target="#addModal" data-whatever="新建文件夹">
                        <i class="fa fa-plus-circle" aria-hidden="true">新建文件夹</i>
                    </a>
                </div>
            </div>
	     {% if file_list %}
            <div class="panel-body">
                <div class="col-sm-12 file-list">
                    <table class="table table-striped">
                        <thead>
                        <tr>
                            <th>名称</th>
                            <th>文件大小</th>
                            <th>更新者</th>
                            <th>更新时间</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="row-list">
			
                        {% for file_obj in file_list %}
                            <tr>
                                <td>
                                    {% if file_obj.file_type == 2 %}
                                        <a href="{% url 'file' project_id=request.tracer.project.id %}?folder={{ file_obj.id }}">
                                            <i class="fa fa-folder" aria-hidden="true" style="color: #ff9e59"></i>
                                            &nbsp;<span style="color: gray">{{ file_obj.name }}</span>
                                        </a>
                                    {% else %}
                                        <a href="{{ file_obj.file_path }}" style="color: black"><i class="fa fa-file"
                                                                                       aria-hidden="true"
                                        ></i>
                                            &nbsp;{{ file_obj.name }}</a>

                                    {% endif %}
                                </td>
                                <td>
                                    {% if file_obj.file_type == 2 %}
                                        -
                                    {% else %}
                                        {{ file_obj.file_size }}
                                    {% endif %}
                                </td>
                                <td>{{ file_obj.update_user.username }}</td>
                                <td>{{ file_obj.update_datetime | date:'Y-m-d H:i:s' }}</td>
                                <td>
                                    {% if file_obj.file_type == 2 %}
                                        <a class="btn btn-xs btn-primary"
                                           data-toggle="modal"
                                           data-target="#addModal"
                                           data-whatever="修改文件夹名"
                                           data-name="{{ file_obj.name }}"
                                           data-fid="{{ file_obj.id }}">
                                            <i class="fa fa-pencil-square-o"
                                               aria-hidden="true"></i></a>
                                    {% else %}
                                        <a href="{% url 'download' project_id=request.tracer.project.id file_id=file_obj.id %}"
                                           class="btn btn-default btn-xs download">
                                            <i class="fa fa-cloud-download" aria-hidden="true"></i>
                                        </a>
                                    {% endif %}
                                    <a href="" class="btn btn-xs btn-danger"
                                       data-toggle="modal"
                                       data-target="#delModal"
                                       data-fid="{{ file_obj.id }}"
                                    ><i class="fa fa-trash"
                                        aria-hidden="true"></i></a>
                                </td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
		{% else %}
                <div class="panel-body text-center">
                <span style="color:grey ">无内容</span>
                </div>
            {% endif %}
        </div>
    </div>
    {#  模态对话框 #}
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title" id="myModalLabel"></h4>
                </div>
                <div class="modal-body">
                    <form id="file-form">
                        {% csrf_token %}
                        <input class="hide" type="text" name="fid" id="fid">
                        {% for field in form %}
                            <div class="form-group">
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                {{ field }}
                                <span class="err-msg"></span>
                            </div>
                        {% endfor %}
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal" id="cancel">取消
                    </button>
                    <button type="button" class="btn btn-primary" id="save">保存</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4>确认删除此文件/文件夹?</h4>
                <p>文件夹包含的所有文件将被删除！</p>
                <p style="text-align: right">
                    <button type="button" class="btn btn-danger" id="delBtn">确认</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                </p>
            </div>
        </div>
    </div>
    {#    进度条显示#}
    <div id="uploadProgress" class="upload-progress hide">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <i class="fa fa-cloud-upload" aria-hidden="true">上传进度</i>
            </div>
            <table class="table">
                <tbody id="progress-list">
                {#                    <tr>...</tr>#}
                </tbody>
            </table>
        </div>
    </div>

    {#    进度条模板#}
    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name">文件名</div>
                    <div class="progress">
                        <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0"
                             aria-valuemax="100" style="width: 0;">
                            0%
                        </div>
                    </div>
                    <div class="progress-error"></div>
                </td>
            </tr>
        </table>
    </div>
    {#    动态显示上传的文件模板#}
    <div class="hide">
        <table id="rowTemplate">
            <tr>
                <td><i class="fa fa-file" aria-hidden="true"></i>
                    <span class="name"></span>
                </td>
                <td class="file_size"></td>
                <td class="update_user"></td>
                <td class="update_time"></td>
                <td>
                    <a href="" class="btn btn-default btn-xs download">
                        <i class="fa fa-cloud-download" aria-hidden="true"></i>
                    </a>
                    <a href="" class="btn btn-xs btn-danger delete"
                       data-toggle="modal"
                       data-target="#delModal">
                        <i class="fa fa-trash" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>
{% endblock %}

{% block js %}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        $(function () {
            initAddModal();
            initDelModal();
        })


        function initAddModal() {
            $('#addModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget);
                var recipient = button.data('whatever');
                var name = button.data('name');
                var fid = button.data('fid');
                var modal = $(this);
                modal.find('.modal-title').text(recipient);

                if (fid) {
                    // 编辑
                    $('#id_name').val(name) // 编辑框获取原来的文件名
                    modal.find('#fid').val(fid)
                } else {
                    // 新建
                    modal.find('.err-msg').empty();
                    $('#file-form')[0].reset();
                }

            })
        }

        function initDelModal() {
            $('#delModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget);
                var fid = button.data('fid');
                var modal = $(this);
                // 找到确认按钮的id 为此添加一个属性 fid = fid
                $('#delBtn').attr('fid', fid)
            })
        }

        $('.err-msg').text(''); // 初始化错误信息
        $('#save').click(function () {
            $.ajax({
                url: location.href, // 请求当前访问页
                type: 'post',
                dataType: "JSON",
                data: $('#file-form').serialize(),
                success: function (data) {
                    if (data.status) {
                        console.log(data.status);
                        location.href = location.href;
                    } else {
                        // 验证失败，前面输入框显示错误信息的
                        $.each(data.error, function (key, value) {
                            // key error 字典里的key 即字段名
                            $('#id_' + key).next().text(value[0])
                            setTimeout(function () {
                                $('.err-msg').text('');
                            }, 2000)
                        })
                    }
                }
            })
        })

        // 删除操作
        $('#delBtn').click(function () {
            // 获取要删除的文件夹的id
            $.ajax({
                url: '{% url 'file_delete' project_id=request.tracer.project.id %}',
                type: 'get',
                data: {'fid': $(this).attr('fid')},
                success: function (data) {
                    if (data.status) {
                        location.href = location.href
                    }

                }
            })
        })

        // 选择上传的文件或者 文件列表
        $('#uploadFile').change(function () {
            $('#progress-list').empty()
            var fileList = $(this)[0].files; // 获取所有的文件对象
            var checkFileList = []; // 获取上传的文件列表 包含文件名和文件大小的字典
            $.each(fileList, function (index, fileObj) {
                var fileName = fileObj.name // 文件名
                var fileSize = fileObj.size // 文件大小
                checkFileList.push({'name': fileName, 'size': fileSize})
            });
            // 上传文件（异步）
            // 获取临时凭证前，需要对文件大小发给django后台，通过post请求，后来验证文件大小
            // 获取临时凭证,定义cos 对象
            var cos = new COS({
                getAuthorization: function (options, callback) {
                    // 想django后台发送请求，获取临时凭证
                    // $.ajax({type:"GET"})
                    $.post('{% url 'cos_credential' project_id=request.tracer.project.id %}', JSON.stringify(checkFileList), function (data) {

                        if (data.status) {
                            var credentials = data.data && data.data.credentials;
                            if (!data.data || !credentials) return console.error('credentials invalid');
                            callback({
                                TmpSecretId: credentials.tmpSecretId,
                                TmpSecretKey: credentials.tmpSecretKey,
                                XCosSecurityToken: credentials.sessionToken,
                                StartTime: data.data.startTime,
                                ExpiredTime: data.data.expiredTime,
                            });
                            // 获取凭证成功，显示上传进度
                            $('#uploadProgress').removeClass('hide')
                        } else {
                            alert(data.error);
                            location.href = location.href
                        }

                    });
                }
            });
            // 应用对象
            $.each(fileList, function (index, fileObj) {
                var fileName = fileObj.name; // 文件名
                var fileSize = fileObj.size; // 文件大小
                var now = (new Date()).getTime();
                var key = now + '_' + fileName; // 存储在cos中的文件名
                var folder_id = "{{ folder_obj.id }}";

                // 进度条开发
                var tr = $('#progressTemplate').find('tr').clone(); // 拷贝进度条模板
                tr.find('.name').text(fileName); // 修改需要显示上传的文件名
                // 添加到上传进度条显示位置
                $('#progress-list').append(tr);

                cos.putObject({
                    Bucket: '{{ request.tracer.project.bucket }}', /* 必须 */
                    Region: '{{ request.tracer.project.region }}',     /* 存储桶所在地域，必须字段 */
                    Key: key,              /* 必须 */
                    StorageClass: 'STANDARD',
                    Body: fileObj, // 上传文件对象
                    onProgress: function (progressData) {
                        {#console.log("文件上传进度--->", fileName, JSON.stringify(progressData));#}
                        // 显示进度
                        var percent = progressData.percent * 100 + '%';
                        tr.find('.progress-bar').text(percent)
                        tr.find('.progress-bar').css('width', percent)

                    }
                }, function (err, data) {
                    {#console.log(err || data);#}
                    if (data && data.statusCode === 200) {
                        // 给后端发送数据
                        $.post('{% url 'file_post' project_id=request.tracer.project.id %}', {
                            name: fileName,
                            file_size: fileSize,
                            key: key,
                            parent: folder_id, //当前目录的id
                            file_path: data.Location, // cos中文件路径
                            etag: data.ETag
                        }, function (data) {
                            // 在数据库中写入成功，将已添加的数据在页面动态展示
                            var newTr = $('#rowTemplate').find('tr').clone() // 克隆模板
                            // 给对应的td赋值，后端传入的
                            newTr.find('.name').text(data.data.name)
                            newTr.find('.file_size').text(data.data.file_size)
                            newTr.find('.update_user').text(data.data.update_user)
                            newTr.find('.update_time').text(data.data.update_time)
                            newTr.find('.delete').attr('data-fid', data.data.id)
                            newTr.find('.download').attr('href', data.data.download_url)
                            // 添加到列表的tbody下
                            $('#row-list').append(newTr)
                            // 移除进度条
                            tr.remove()
				location.href = location.href
                        })
                    } else {
                        tr.find('.progress-error').text('上传失败');
                    }
                });
            })
        })
    </script>
{% endblock %}
